#include "devicemanagement.h"
#include "ui_devicemanagement.h"
#include "devicedialog.h"
#include "databasemanager.h"
#include <QMessageBox>
#include <QMenu>
#include <QInputDialog>
#include <QDebug>

DeviceManagement::DeviceManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DeviceManagement),
    dbManager(nullptr)
{
    ui->setupUi(this);
    setupTable();
    setupConnections();
}

void DeviceManagement::setDatabaseManager(DatabaseManager* manager) {
    dbManager = manager;
    refreshDeviceList();
}


DeviceManagement::~DeviceManagement()
{
    delete ui;
}

void DeviceManagement::setupTable()
{
    // 设置表头
    QStringList headers;
    headers << "设备ID" << "设备名称" << "类型" << "位置" << "制造商"
            << "型号" << "状态" << "安装日期";
    ui->tableDevices->setHorizontalHeaderLabels(headers);

    // 设置表格属性
    ui->tableDevices->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableDevices->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableDevices->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableDevices->horizontalHeader()->setStretchLastSection(true);
    ui->tableDevices->setColumnHidden(0, true); // 隐藏ID列

    // 初始化分组树
    ui->treeWidgetGroups->setHeaderLabels(QStringList() << "分组名称" << "设备数量");
}

void DeviceManagement::setupConnections()
{
    // 按钮连接
    connect(ui->btnAddDevice, &QPushButton::clicked, this, &DeviceManagement::onAddDevice);
    connect(ui->btnSearch, &QPushButton::clicked, this, &DeviceManagement::onSearchDevice);
    connect(ui->comboBoxGroupFilter, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &DeviceManagement::onGroupFilterChanged);
    connect(ui->btnCreateGroup, &QPushButton::clicked, this, &DeviceManagement::onCreateGroup);

    // 右键菜单
    ui->tableDevices->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->tableDevices, &QTableWidget::customContextMenuRequested,
            this, &DeviceManagement::showContextMenu);
}

void DeviceManagement::refreshDeviceList()
{
    ui->tableDevices->setRowCount(0);

    QString sql = "SELECT device_id, name, type, location, manufacturer, "
                 "model, status, installation_date FROM devices";

    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        QMessageBox::critical(this, "错误", "查询设备失败: " + response.mid(6));
        return;
    }

    if (response == "No results found") {
        return;
    }

    // 解析服务器返回的数据
    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList columns = row.split("|", QString::SkipEmptyParts);
        if (columns.size() < 8) continue;

        int currentRow = ui->tableDevices->rowCount();
        ui->tableDevices->insertRow(currentRow);

        for (int col = 0; col < columns.size(); ++col) {
            QTableWidgetItem *item = new QTableWidgetItem(columns[col].trimmed());
            ui->tableDevices->setItem(currentRow, col, item);
        }
    }
}

void DeviceManagement::refreshGroupList()
{
    ui->treeWidgetGroups->clear();

    // 按类型分组
    QString typeResponse = dbManager->sendRequest("SELECT type, COUNT(*) FROM devices GROUP BY type");
    if (!typeResponse.startsWith("Error:")) {
        QTreeWidgetItem *typeGroup = new QTreeWidgetItem(ui->treeWidgetGroups);
        typeGroup->setText(0, "按类型分组");

        QStringList typeRows = typeResponse.split("\n", QString::SkipEmptyParts);
        foreach (const QString &row, typeRows) {
            QStringList cols = row.split(" | ", QString::SkipEmptyParts);
            if (cols.size() == 2) {
                QTreeWidgetItem *item = new QTreeWidgetItem(typeGroup);
                item->setText(0, cols[0].trimmed());
                item->setText(1, cols[1].trimmed());
            }
        }
    }

    // 按位置分组
    QString locationResponse = dbManager->sendRequest("SELECT location, COUNT(*) FROM devices GROUP BY location");
    if (!locationResponse.startsWith("Error:")) {
        QTreeWidgetItem *locationGroup = new QTreeWidgetItem(ui->treeWidgetGroups);
        locationGroup->setText(0, "按位置分组");

        QStringList locationRows = locationResponse.split("\n", QString::SkipEmptyParts);
        foreach (const QString &row, locationRows) {
            QStringList cols = row.split(" | ", QString::SkipEmptyParts);
            if (cols.size() == 2) {
                QTreeWidgetItem *item = new QTreeWidgetItem(locationGroup);
                item->setText(0, cols[0].trimmed());
                item->setText(1, cols[1].trimmed());
            }
        }
    }

    ui->treeWidgetGroups->expandAll();
}

void DeviceManagement::showContextMenu(const QPoint &pos)
{
    QMenu menu(this);
    QAction *editAction = menu.addAction("编辑设备");
    QAction *deleteAction = menu.addAction("删除设备");

    connect(editAction, &QAction::triggered, this, &DeviceManagement::onEditDevice);
    connect(deleteAction, &QAction::triggered, this, &DeviceManagement::onDeleteDevice);

    menu.exec(ui->tableDevices->viewport()->mapToGlobal(pos));
}

void DeviceManagement::onAddDevice()
{
    DeviceDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        QString insertSql = QString(
            "INSERT INTO devices (name, type, location, manufacturer, model, status, installation_date) "
            "VALUES ('%1', '%2', '%3', '%4', '%5', '%6', '%7')"
        )
        .arg(dialog.getDeviceName().replace("'", "''"))
        .arg(dialog.getDeviceType().replace("'", "''"))
        .arg(dialog.getLocation().replace("'", "''"))
        .arg(dialog.getManufacturer().replace("'", "''"))
        .arg(dialog.getModel().replace("'", "''"))
        .arg(dialog.getStatus())
        .arg(dialog.getInstallationDate().toString("yyyy-MM-dd"));

        QString response = dbManager->sendRequest(insertSql);

        if (response.startsWith("Error:")) {
            QMessageBox::critical(this, "错误", "添加设备失败: " + response.mid(6));
            return;
        }

        // 简化判断，只要不是错误就认为是成功
        refreshDeviceList();
        refreshGroupList();
        QMessageBox::information(this, "成功", "设备添加成功");
    }
}

void DeviceManagement::onEditDevice()
{
    QModelIndexList selected = ui->tableDevices->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要编辑的设备");
        return;
    }

    int row = selected.first().row();
    QString deviceId = ui->tableDevices->item(row, 0)->text();

    DeviceDialog dialog(this);
    dialog.setDeviceName(ui->tableDevices->item(row, 1)->text());
    dialog.setDeviceType(ui->tableDevices->item(row, 2)->text());
    dialog.setLocation(ui->tableDevices->item(row, 3)->text());
    dialog.setManufacturer(ui->tableDevices->item(row, 4)->text());
    dialog.setModel(ui->tableDevices->item(row, 5)->text());
    dialog.setStatus(ui->tableDevices->item(row, 6)->text());
    dialog.setInstallationDate(QDate::fromString(ui->tableDevices->item(row, 7)->text(), "yyyy-MM-dd"));

    if (dialog.exec() == QDialog::Accepted) {
        QString sql = QString("UPDATE devices SET name='%1', type='%2', location='%3', "
                            "manufacturer='%4', model='%5', status='%6', installation_date='%7' "
                            "WHERE device_id=%8")
                            .arg(dialog.getDeviceName().replace("'", "''"))
                            .arg(dialog.getDeviceType().replace("'", "''"))
                            .arg(dialog.getLocation().replace("'", "''"))
                            .arg(dialog.getManufacturer().replace("'", "''"))
                            .arg(dialog.getModel().replace("'", "''"))
                            .arg(dialog.getStatus())
                            .arg(dialog.getInstallationDate().toString("yyyy-MM-dd"))
                            .arg(deviceId);

        QString response = dbManager->sendRequest(sql);
        // 修改这里的判断条件
        if (!response.startsWith("Error:")) {
            refreshDeviceList();
            refreshGroupList();
            QMessageBox::information(this, "成功", "设备更新成功");
        } else {
            QMessageBox::critical(this, "错误", "更新设备失败: " + response);
        }
    }
}

void DeviceManagement::onDeleteDevice()
{
    QModelIndexList selected = ui->tableDevices->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的设备");
        return;
    }

    int row = selected.first().row();
    QString deviceId = ui->tableDevices->item(row, 0)->text();
    QString deviceName = ui->tableDevices->item(row, 1)->text();

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除",
                                QString("确定要删除设备【%1】吗？此操作不可撤销！").arg(deviceName),
                                QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        // 先删除关联的状态历史记录
        QString historySql = QString("DELETE FROM device_status_history WHERE device_id = %1").arg(deviceId);
        QString historyResponse = dbManager->sendRequest(historySql);

        // 再删除主设备记录
        QString deviceSql = QString("DELETE FROM devices WHERE device_id = %1").arg(deviceId);
        QString deviceResponse = dbManager->sendRequest(deviceSql);

        // 修改这里的判断条件
        if (!deviceResponse.startsWith("Error:")) {
            refreshDeviceList();
            refreshGroupList();
            QMessageBox::information(this, "成功", "设备删除成功");
        } else {
            QMessageBox::critical(this, "错误", "删除设备失败: " + deviceResponse);
        }
    }
}

void DeviceManagement::onSearchDevice()
{
    QMutexLocker lock(&m_mutex);
    if (!dbManager) {
        qDebug() << "Error: dbManager is nullptr!";
        return;
    }

    QString keyword = ui->lineEditSearch->text().trimmed();

    for (int i = 0; i < ui->tableDevices->rowCount(); ++i) {
        bool match = false;
        for (int j = 1; j < ui->tableDevices->columnCount(); ++j) { // 跳过ID列
            QTableWidgetItem* item = ui->tableDevices->item(i, j);
            if (item && item->text().contains(keyword, Qt::CaseInsensitive)) {
                match = true;
                break;
            }
        }
        ui->tableDevices->setRowHidden(i, !match && !keyword.isEmpty());
    }
}

void DeviceManagement::onGroupFilterChanged(int index)
{
    QString filter;
    switch (index) {
    case 1: // 按类型分组
        filter = ui->comboBoxGroupFilter->currentText();
        if (filter != "按类型分组") {
            for (int i = 0; i < ui->tableDevices->rowCount(); ++i) {
                bool visible = (ui->tableDevices->item(i, 2)->text() == filter);
                ui->tableDevices->setRowHidden(i, !visible);
            }
        }
        break;
    case 2: // 按位置分组
        filter = ui->comboBoxGroupFilter->currentText();
        if (filter != "按位置分组") {
            for (int i = 0; i < ui->tableDevices->rowCount(); ++i) {
                bool visible = (ui->tableDevices->item(i, 3)->text() == filter);
                ui->tableDevices->setRowHidden(i, !visible);
            }
        }
        break;
    default: // 所有设备
        for (int i = 0; i < ui->tableDevices->rowCount(); ++i) {
            ui->tableDevices->setRowHidden(i, false);
        }
        break;
    }
}

void DeviceManagement::onCreateGroup()
{
    QString groupName = QInputDialog::getText(this, "创建分组", "请输入分组名称:");
    if (!groupName.isEmpty()) {
        // 这里可以添加创建分组的数据库操作
        QMessageBox::information(this, "成功", QString("分组 '%1' 创建成功").arg(groupName));
        refreshGroupList();
    }
}

